package com.example.jwtauthdemo.controller;


import com.example.jwtauthdemo.entity.ClassUser;
import com.example.jwtauthdemo.entity.CreateClass;
import com.example.jwtauthdemo.model.User;
import com.example.jwtauthdemo.service.AuthService;
import com.example.jwtauthdemo.service.impl.ClassServceImpl;
import com.example.jwtauthdemo.service.insertClassUserService;
import com.example.jwtauthdemo.service.StudentManageService;
import com.example.jwtauthdemo.util.*;
import com.example.jwtauthdemo.vo.CreateClassVo;
import com.example.jwtauthdemo.dto.TeacherApplyClassRequest;
import com.example.jwtauthdemo.util.Result;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ClassController {
    private static final Logger logger = LoggerFactory.getLogger(ClassController.class);

    @Autowired
    private ClassServceImpl classServce;

    @Autowired
    private Random6 random6;
    @Autowired
    private Uuid uuid;

    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private insertClassUserService insertClassUser;

    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private StudentManageService studentManageService;

    //解散班级
    @DeleteMapping("/class/dissolve")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> dissolveClass(@RequestParam String classCode, @RequestHeader("Authorization") String authorizationHeader) {
        try {
            String jwt = authorizationHeader.substring(7);
            String teacherId = jwtUtil.extractUserId(jwt);
            classServce.dissolveClass(teacherId, classCode);
            return Result.success("班级解散成功");
        } catch (RuntimeException e) {
            return Result.error(500, e.getMessage());
        }
    }


    //创建班级
    @PostMapping("/insertClass")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> insertClass(@ModelAttribute CreateClassVo createClassVo, @RequestHeader("Authorization") String authorizationHeader){
        String jwt = authorizationHeader.substring(7);
        String teacherId = jwtUtil.extractUserId(jwt);
        // 获取上传的图片文件
        MultipartFile file = createClassVo.getFile();
        System.out.println("file: " + file);

        String imageUrl = minioUtil.uploadImage(file);

        CreateClass createClass = new CreateClass(
               null,
                createClassVo.getName(),
                createClassVo.getSubject(),
                createClassVo.getGrade(),
                createClassVo.getDescription(),
                createClassVo.getSemester(),
                imageUrl,
                null,
                teacherId
        );
        // 先生成班级码
        String classCodeStr = random6.getRandNum();
        createClass.setClassCode(classCodeStr);
        // 将班级码转换为Integer作为id
        createClass.setId(Integer.parseInt(classCodeStr));
        
        // 获取当前用户的角色信息
        User user = authService.getCurrentUser();
        Integer role = user.getRole();
        
        ClassUser classUser = new ClassUser(
                createClass.getTeacherId(),
                createClass.getClassCode(),
                role, 1
        );
        insertClassUser.insertClassUser(classUser);
         classServce.insertClass(createClass);
         return Result.success(createClass);
    }
    //查询班级
    @GetMapping("/classes")
    @PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
    public Result<List<CreateClass>> getTeacherClasses(@RequestHeader("Authorization") String authorizationHeader) {
        try {
            String jwt = authorizationHeader.substring(7);
            String userId = jwtUtil.extractUserId(jwt);
            
            // 获取当前用户信息以确定角色
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = authService.getCurrentUser();
            Integer role = user.getRole();
            
            List<CreateClass> classes;
            if (role == 2) {
                // 班主任角色：直接查询其创建的班级
                classes = classServce.selectClassesByTeacherId(userId);
            } else {
                // 老师角色：通过user_class_relation表查询关联的班级
                classes = classServce.selectClassesByUserIdAndRole(userId, role);
            }
            
            return Result.success(classes);
        } catch (RuntimeException e) {
            logger.error("获取班级列表失败: {}", e.getMessage(), e);
            return Result.error(500, "获取班级列表失败: " + e.getMessage());
        }
    }

    //发送加入班级请求
    @PostMapping("/class/apply")
    @PreAuthorize("hasRole('TEACHER')")
    public Result<String> teacherApplyForClass(@RequestBody TeacherApplyClassRequest request, @RequestHeader("Authorization") String authorizationHeader) {
        try {
            // 从Authorization头中提取JWT并获取教师ID
            String jwt = authorizationHeader.substring(7);
            String teacherIdStr = jwtUtil.extractUserId(jwt);
            Integer teacherId = Integer.parseInt(teacherIdStr);
            
            // 获取班级编码（String类型）并转换为Integer
            String classCodeStr = request.getClassCode();
            Integer classCode = Integer.parseInt(classCodeStr);
            
            // 设置状态为0（待同意）
            Integer status = 0;
            
            // 调用服务层方法
            studentManageService.teacherApplyForClass(teacherId, classCode, status);
            
            return Result.success("申请已发送，请等待审核");
        } catch (NumberFormatException e) {
            logger.error("ID格式错误: {}", e.getMessage());
            return Result.error(400, "ID格式错误（教师ID或班级编码）");
        } catch (RuntimeException e) {
            logger.error("申请加入班级失败: {}", e.getMessage(), e);
            return Result.error(500, "申请加入班级失败: " + e.getMessage());
        }
    }

}